package com.ruoyi.mqtt.config;

import com.ruoyi.mqtt.pojo.MqttLogs;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @program: RuoYi-Cloud-master
 * @ClassName WebSocket
 * @description:
 * @author:
 * @create: 2023-11-30 21:38
 * @Version 1.0
 **/

@ServerEndpoint("/trapeze/trapeze")
@Component
public class WebSocket {

    private Session session;

    private static final Set<WebSocket> connections = new CopyOnWriteArraySet<>();

    /**
     * 当有ws 客户端连接进来，调用的方法
     * 处理连接事件
     * @param session
     */
    @OnOpen
    public void start(Session session) {
        this.session = session;
        System.out.println("this:" + this);
        String msg = String.format(session.toString());
        System.out.println(msg);

        connections.add(this);
//        broadcast(msg);
    }

    /**
     * 接收到消息的监听方法
     * client write    ------>   server  read
     * server write    ------>   client  read
     */
    @OnMessage
    public void incoming(String message) {
        session = this.session;
        String msg = String.format(message,session.toString());
        System.out.println("incoming: "+msg);
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void end(Session session) {
        connections.remove(this);
        String msg = String.format(session.toString());
//        broadcast(msg);
    }
    /**
     * 出错了
     * @param t
     * @throws Throwable
     */
    @OnError
    public void onError(Throwable t) throws Throwable {
        System.out.println("onError");
        t.printStackTrace();
    }

    /**
     * 广播消息
     * @param msg
     */
    private void broadcast(String msg) {
        for (WebSocket client : connections) {
            try {
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }
        }
        System.err.println(msg);
    }
}
